//
//  PAAsynMedialButton.m
//  PAMobileWallet
//
//  Created by Gavin Zhang on 7/26/13.
//  Copyright (c) 2013 平安付. All rights reserved.
//

#import "PAAsynMedialButton.h"
#import "PAMediaRequest.h"
#import "PAMediaAsynManager.h"
#import <AVFoundation/AVFoundation.h>

@interface PAAsynMedialButton ()
@property(nonatomic, strong)PAMediaRequest *request;

@end

@implementation PAAsynMedialButton

@synthesize uniqueId            = _uniqueId;
@synthesize mediaUrl            = _mediaUrl;
@synthesize request             = _request;
@synthesize cornerRadius        = _cornerRadius;
@synthesize player;
@synthesize tradeDirection;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        //
        self.contentMode = UIViewContentModeScaleToFill;
    }
    return self;
}
- (void)setCornerRadius:(float)cornerRadius
{
    
    _cornerRadius = cornerRadius;
}
- (id)initWithUrl:(NSString *)url
{
    if (self){
        self.mediaUrl = url;
    }
    return self;
}

- (void)setMediaUrl:(NSString *)mediaUrl
{
    /*
     * 应该有 比较是否需要更新的机制
     */
    _mediaUrl = [mediaUrl copy];
}

- (void)setSelected:(BOOL)selected
{
    if (selected) {
        [self loadMediaFromUrl];
    }

}

- (void)stopUpdate
{
    
}


- (BOOL) isMediaLocal
{
    if(self.mediaUrl == nil || [self.mediaUrl length] == 0)
        return FALSE;
    
    NSString *audioPath = [self buildMediaPathWithUniqueID:self.uniqueId];
    if ([[NSFileManager defaultManager] fileExistsAtPath:audioPath])
        return TRUE;
    
    return FALSE;
}

-(NSString*) buildMediaPathWithUniqueID:(NSString*) uniqueID
{
    return [[DocumentsPath stringByAppendingPathComponent:self.uniqueId] stringByAppendingPathExtension:@"wav"];
}

- (void)loadMediaFromUrl
{
    if (self.mediaUrl) {
        NSString *audioPath = [self buildMediaPathWithUniqueID:self.uniqueId];
        if ([[NSFileManager defaultManager] fileExistsAtPath:audioPath]) {
            [self playAudioWithPath:audioPath];
        }else{
            self.request = [[PAMediaRequest alloc] initWithURL:[NSURL URLWithString:self.mediaUrl]];
            self.request.paMediaAsynDelegate = self;
            self.request.uniqueId = self.uniqueId;
            [[PAMediaAsynManager sharedInstance] loadMediaWithRequest:self.request];
        }
    }
}
- (void)playAudioWithPath:(NSString *)path
{
    NSError * error = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (nil == error) {
        [player setVolume:1.0];
        if([player prepareToPlay]){
            NSLog(@"播放");
            [player play];
        }else{
            NSLog(@"播放准备失败");
        }
    }else{
        NSLog(@"初始化播放器失败");
    }
}
#pragma mark - PAImageAsynDelegate
- (void)paMediaRequestStarted
{
}
- (void)paMediaRequestSuccess:(NSString *)filePath
{
    [self showTrackTimeIfPossible:self.tradeDirection];
    [self playAudioWithPath:filePath];
}
- (void)paMediaRequestFailed
{
}
#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    self.selected = NO;
}

-(int) getTrackDuration:(NSString*) path
{
    NSError * error = nil;
    AVAudioPlayer* tmpPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if(!tmpPlayer)
        return 0;
    
    return tmpPlayer.duration;
}

- (void)showTrackTimeIfPossible:(int) tradeDirection
{
    if(![self isMediaLocal])
        return;
    
    CGRect outter = self.frame;
    static double coefficient = 0.5;
    
    CGRect inner;
    inner.origin.x = outter.size.width * (1 - coefficient) / 2.0f;
    inner.origin.y = outter.size.height * (1 - coefficient) / 2.0f;
    inner.size.width = outter.size.width * coefficient;
    inner.size.height = outter.size.height * coefficient;
    
    UILabel *timeLAB = [[UILabel alloc] initWithFrame:inner];
    [timeLAB setFont:[UIFont fontWithName:@"Helvetica" size:10.0]];
    NSString* path = [self buildMediaPathWithUniqueID:self.uniqueId];
    int trackDuration = [self getTrackDuration:path];
    timeLAB.text = [NSString stringWithFormat:@"%d'", trackDuration];
    
    CGAffineTransform trans;
    if(tradeDirection == TDT_Out)
    {
        trans = CGAffineTransformMakeRotation(M_PI);
        trans = CGAffineTransformTranslate(trans, -28.0f, 0.0f);
    }
    else
    {
        trans = CGAffineTransformMakeRotation(M_PI * 2);
        trans = CGAffineTransformTranslate(trans, 28.0f, 0.0f);
    }
    [timeLAB setTransform:trans];
    
    [self addSubview:timeLAB];
}
@end
